package dat255.calendarclock.controller.event;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import dat255.calendarclock.R;
import dat255.calendarclock.controller.event.activity.CreateCategoryActivity;
import dat255.calendarclock.controller.event.activity.DayPickerActivity;
import dat255.calendarclock.model.event.Category;
import dat255.calendarclock.model.event.CategoryComparator;
import dat255.calendarclock.model.event.DateHelper;
import dat255.calendarclock.model.event.Event;
import dat255.calendarclock.model.event.EventHandler;

/**
 * The activity that makes it possible to add events to the calendar.
 * 
 * @author Oskar Montin, Marcus Hultman & Gabriel Andersson
 * 
 */
public class AddEventController extends Activity {
	// Fields
	private static boolean isInitialized = false;

	private static TextView titleText;
	private static EditText nameTextField;
	private static EditText descTextField;
	private static Spinner categorySpinner;
	private static ArrayAdapter<Category> categorySpinnerAdapter;
	private static Category newCategoryOption;
	private static Button editDateButton;
	private static TimePicker timePicker;
	private static CheckBox recurringCheckBox;
	private static LinearLayout recurringLayout;
	private static RadioButton weeklyRadioButton;
	private static RadioButton monthlyRadioButton;
	private static LinearLayout weeklyLayout;
	private static ToggleButton[] weeklyToggleButtons;
	private static LinearLayout monthlyLayout;
	private static Spinner recurringSpinner;
	private static ArrayAdapter<String> recurringWeeklyAdapter;
	private static ArrayAdapter<String> recurringMonthlyAdapter;
	private static ArrayList<String> recurringWeeklyOptions = new ArrayList<String>();
	private static ArrayList<String> recurringMonthlyOptions = new ArrayList<String>();
	private static Button saveButton;
	private static Button removeButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.modifyevent_layout);
		if (!isInitialized)
			init();
		resetFields();
	}

	@Override
	protected void onResume() {
		super.onResume();
		updateFields();
	}

	/**
	 * initializes the fields
	 */
	private void init() {
		// Title
		titleText = (TextView) findViewById(R.id.eventDetails_Title);
		titleText.setText("Add Event");
		// Name
		nameTextField = (EditText) findViewById(R.id.eventDetails_nameTextField);
		// Description
		descTextField = (EditText) findViewById(R.id.eventDetails_descTextField);
		// Category spinner
		newCategoryOption = Category.createCategory("New Category...",
				Color.WHITE);
		categorySpinner = (Spinner) findViewById(R.id.eventDetails_categorySpinner);
		categorySpinnerAdapter = new ArrayAdapter<Category>(
				getApplicationContext(), android.R.layout.simple_spinner_item,
				new ArrayList<Category>(EventHandler.getInstance()
						.getAllCategories()));
		if (!(EventHandler.getInstance().getAllCategories().contains(Category
				.createCategory())))
			categorySpinnerAdapter.add(Category.createCategory());
		if (!(EventHandler.getInstance().getAllCategories()
				.contains(newCategoryOption)))
			categorySpinnerAdapter.add(newCategoryOption);
		categorySpinner.setAdapter(categorySpinnerAdapter);
		categorySpinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		categorySpinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> adapter,
							View view, int i, long lng) {
						if (i == AddEventController.categorySpinnerAdapter
								.getPosition(newCategoryOption)) {
							AddEventController.categorySpinner.setSelection(0);
							startActivity(new Intent(AddEventController.this,
									CreateCategoryActivity.class));
						}
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}

				});
		// Date
		editDateButton = (Button) findViewById(R.id.eventDetails_dayPicker);
		// Time
		timePicker = (TimePicker) findViewById(R.id.eventDetails_timePicker);
		timePicker.setIs24HourView(true);

		// Recurring
		{
			recurringCheckBox = (CheckBox) findViewById(R.id.eventDetails_reccurringCheckBox);
			recurringLayout = (LinearLayout) findViewById(R.id.eventDetails_reccurringLayout);
			// Radio buttons
			weeklyRadioButton = (RadioButton) findViewById(R.id.eventDetails_weeklyRadioButton);
			monthlyRadioButton = (RadioButton) findViewById(R.id.eventDetails_monthlyRadioButton);
			// Layouts
			weeklyLayout = (LinearLayout) findViewById(R.id.eventDetails_weeklyLayout);
			monthlyLayout = (LinearLayout) findViewById(R.id.eventDetails_monthlyLayout);
			// ToggleButtons
			weeklyToggleButtons = new ToggleButton[] {
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonMon),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonTue),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonWed),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonThu),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonFri),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonSat),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonSun) };
			// Spinner with options
			recurringSpinner = (Spinner) findViewById(R.id.eventDetails_recurringSpinner);
			recurringWeeklyOptions.add(getString(R.string.every_week));
			recurringWeeklyOptions.add(getString(R.string.every_other_week));
			recurringWeeklyOptions.add(getString(R.string.every_third_week));
			recurringWeeklyOptions.add(getString(R.string.every_fourth_week));
			recurringWeeklyAdapter = new ArrayAdapter<String>(
					getApplicationContext(),
					android.R.layout.simple_spinner_item,
					recurringWeeklyOptions);
			recurringMonthlyOptions.add(getString(R.string.every_month));
			recurringMonthlyAdapter = new ArrayAdapter<String>(
					getApplicationContext(),
					android.R.layout.simple_spinner_item,
					recurringMonthlyOptions);
		}
		// End zone
		saveButton = (Button) findViewById(R.id.eventDetails_doneButton);
		removeButton = (Button) findViewById(R.id.eventDetails_removeEventButton);

	}

	/**
	 * Resets the fields to an initial value
	 */
	private void resetFields() {
		// Category
		categorySpinnerAdapter.sort(new CategoryComparator());
		categorySpinner.setSelection(0);

		// Time
		GregorianCalendar date = new GregorianCalendar();
		int rollValue = date.get(GregorianCalendar.MINUTE) >= 30 ? 60 : 30;
		DateHelper.reset(date, GregorianCalendar.HOUR_OF_DAY);
		date.add(GregorianCalendar.MINUTE, rollValue);
		timePicker.setCurrentHour(date.getTime().getHours());
		timePicker.setCurrentMinute(date.getTime().getMinutes());

		// Recurring section
		weeklyRadioButton.setChecked(true);
		recurringCheckBox.setChecked(false);

		// end zone
		saveButton.setText("Add Event");
		removeButton.setVisibility(View.GONE);

		updateFields();

	}

	/**
	 * Updates the fields Call this when something has changed
	 */
	private void updateFields() {
		// Category
		Category category = EventHandler.getInstance().getCustomCategory();
		if (category != null) {
			categorySpinnerAdapter.add(category);
			categorySpinnerAdapter.sort(new CategoryComparator());
			categorySpinner.setSelection(categorySpinnerAdapter
					.getPosition(category));
		}

		EventHandler.getInstance().setCustomCategory(null);
		// Date
		editDateButton.setText(new SimpleDateFormat("dd MMMM yyyy")
				.format(EventHandler.getInstance().getSelectedDay().getTime()));
		// Recurring Layout
		recurringLayout
				.setVisibility(recurringCheckBox.isChecked() ? View.VISIBLE
						: View.GONE);
		// Layouts
		weeklyLayout.setVisibility(weeklyRadioButton.isChecked() ? View.VISIBLE
				: View.GONE);
		int dayOfWeek = (EventHandler.getInstance().getSelectedDay()
				.get(GregorianCalendar.DAY_OF_WEEK) + 5) % 7;
		for (int i = 0; i < weeklyToggleButtons.length; i++) {
			if (i == dayOfWeek) {
				weeklyToggleButtons[i].setClickable(false);
				weeklyToggleButtons[i].setChecked(true);
			} else {
				weeklyToggleButtons[i].setClickable(true);
				if (!recurringCheckBox.isChecked()) {
					weeklyToggleButtons[i].setChecked(false);
				}
			}
		}
		monthlyLayout
				.setVisibility(monthlyRadioButton.isChecked() ? View.VISIBLE
						: View.GONE);
		// TODO: monthly settings, yearly recurring.
		// TODO: specified date must be marked in month.

		// Spinner for options
		recurringSpinner
				.setAdapter(weeklyRadioButton.isChecked() ? recurringWeeklyAdapter
						: recurringMonthlyAdapter);
		// TODO: OccurringSpinner Strings.
	}

	/**
	 * called when button for edit date is clicked
	 */
	public void editDateButtonClicked(View view) {
		startActivity(new Intent(this, DayPickerActivity.class));

	}

	/**
	 * called when check-box for recurring options is clicked
	 */
	public void reccuringCheckBoxClicked(View view) {
		updateFields();
	}

	/**
	 * called when radio button for weekly recurring is clicked
	 */
	public void weeklyRadioButtonClicked(View view) {
		updateFields();
	}

	/**
	 * called when radio button for monthly recurring is clicked
	 */
	public void monthlyRadioButtonClicked(View view) {
		updateFields();
	}

	/**
	 * If the add event button is clicked this method is called
	 */
	public void doneButtonClicked(View view) {
		// Getting values from fields
		EventHandler eventHandler = EventHandler.getInstance();
		String name = nameTextField.getEditableText().toString();
		String description = descTextField.getEditableText().toString();
		Category category = categorySpinnerAdapter.getItem(categorySpinner
				.getSelectedItemPosition());
		GregorianCalendar date = eventHandler.getSelectedDay();
		date.set(GregorianCalendar.HOUR_OF_DAY, timePicker.getCurrentHour());
		date.set(GregorianCalendar.MINUTE, timePicker.getCurrentMinute());

		// Can not create events in the past.
		if (date.before(new GregorianCalendar())) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					AddEventController.this).create();
			alertDialog.setTitle("The destiny is unclear");
			alertDialog
					.setMessage("The time and date is somehow floating into the past eternity...");
			alertDialog.setButton("Back to the future", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				}
			});
			alertDialog.setIcon(R.drawable.icon);
			alertDialog.show();
			return;
		}

		// TODO: Disabled due to debugging
		// boolean reccuring = reccuringCheckBox.isChecked();
		// TODO: this doesn't look at the interval
		// TODO: Monthly interval..
		// TODO: Occurring different intervals of intervals.

		// Adding event to the event handler
		Event event = new Event(name.length() == 0 ? null : name, description,
				date, category);
		event.getInterval().setTimeOfEvent(timePicker.getCurrentHour(),
				timePicker.getCurrentMinute());
		eventHandler.addEvent(event);
		makeToast(date);
		AddEventController.this.finish();
	}

	/**
	 * This makes a toast when an event is made
	 * 
	 * @param date
	 *            the date the event will occur
	 */
	private void makeToast(GregorianCalendar date) {
		String dateString = new SimpleDateFormat("dd MMMM").format(date
				.getTime());
		String[] dateSplit = dateString.split(" ");

		String suffix = null;
		if (dateSplit[0].endsWith("1"))
			suffix = "st ";
		else if (dateSplit[0].endsWith("2"))
			suffix = "nd ";
		else if (dateSplit[0].endsWith("3"))
			suffix = "rd ";
		else
			suffix = "th ";
		dateString = dateSplit[0] + suffix + dateSplit[1];

		Toast.makeText(
				getApplicationContext(),
				"So I've heard there will happen something legendary on "
						+ dateString, Toast.LENGTH_LONG).show();

	}

}
